import json

from flask import Flask, render_template, request

from api import search

app = Flask(__name__)

mode = 'ui1'


@app.route('/')
def hello_world():
    q = request.args.get('q')
    global mode

    mode = request.args.get('mode', 'ui')
    if q.endswith('-f'):
        q = q[:-2].strip()
        full_mode = True
    else:
        full_mode = False

    ui = request.args.get('ui')
    ui = True
    nodes = list(search(q, full_mode=full_mode))

    if len(nodes) == 0:
        return render_template('index.html', q=q)
    if len(nodes) > 1:
        return render_template('index.html', q=q)
    else:
        if mode == 'ui':
            node = nodes[0]
            descendants = node.render_to_json() if ui else node.render_to_html()
            return render_template('index.html', ancestors=node.ancestors(), siblings=node.siblings(),
                                   descendants=descendants, ui=ui)
        else:
            node = nodes[0]
            print(node.render_to_text())
            return render_template('editor.html', text=node.render_to_text())


@app.route('/api')
def hello_world():
    q = request.args.get('q')
    node = []
    return json.dumps(node.render_to_json())


if __name__ == '__main__':
    app.run(port='8001', host='0.0.0.0', debug=True)
